<template>
  <div class="app-container">
    <!-- 题库试题 -->
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container tree-container">
          <el-tree
            :data="treeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <el-form-item label="题型" prop="theType">
            <el-select
              v-model="queryParams.theType"
              clearable
              placeholder="请选择"
              size="small"
              style="width: 240px"
              @change="handleQuery"
            >
              <el-option
                v-for="item in theTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="关键字"
            prop="keywords"
            style="margin-left: 20px"
          >
            <el-input
              v-model="queryParams.keywords"
              placeholder="请输入试题名称/发布人"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" style="margin-bottom: 10px">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['21110']"
              >添加试题</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              v-hasPermi="['21140']"
              :disabled="multiple"
              @click="handleDelete"
              >批量删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              v-hasPermi="['21150']"
              @click="handleImport"
              >批量导入</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              v-hasPermi="['21160']"
              @click="handleExport"
              >批量导出</el-button
            >
          </el-col>
        </el-row>
        <!-- 列表 -->
        <el-table
          v-loading="loading"
          :data="tableList"
          :border="true"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="试题分类"
            prop="category"
            align="center"
            :show-overflow-tooltip="true"
            width="120"
          />
          <el-table-column
            align="center"
            prop="subject"
            label="试题标题"
            width="360"
          />
          <el-table-column
            label="题型"
            align="center"
            prop="theType"
            width="100"
          >
            <template slot-scope="scope">
              <span>{{ findTheType(scope.row.theType) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="发布时间"
            prop="releaseTime"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="发布人"
            prop="publisher"
            align="center"
            :show-overflow-tooltip="true"
            width="98"
          />
          <el-table-column
            label="状态"
            align="center"
            key="enable"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="100"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['21120']"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['21130']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <!-- <el-button
                size="mini"
                type="text"
                @click="handleDisable(scope.row)"
                >禁用</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pagesize"
          @pagination="getList"
        />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="600px"
          append-to-body
        >
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            :validate-on-rule-change="false"
            label-width="80px"
          >
            <!-- *试题分类（自动）、*题库标题、×题型（单选题、多选题、判断题、填空题），*答案，选项A、选项B、选项C、选择D、选项E -->
            <el-form-item label="试题分类" prop="categoryId">
              <treeselect
                v-model="form.categoryId"
                :options="treeOptions"
                :show-count="true"
                @select="selectTree"
                placeholder="请选择试题分类"
              />
            </el-form-item>
            <el-form-item label="试题标题" prop="subject">
              <el-input
                type="textarea"
                autosize
                placeholder="请输入试题标题"
                v-model="form.subject"
              >
              </el-input>
              <span class="warning">需要填空处请以()表示。</span>
            </el-form-item>
            <el-form-item label="题型" prop="theType">
              <el-select
                v-model="form.theType"
                placeholder="请选择"
                @change="changeTheType"
              >
                <el-option
                  v-for="item in theTypeOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-checkbox-group
              v-model="checkList"
              @change="changeCheckbox"
              :max="max"
              v-if="form.theType != 3"
            >
              <div v-for="(item, index) in options" :key="index">
                <el-form-item :label="item.selectNumber" class="option" :class="{'hide4': form.theType == 4}">
                  <el-input
                    v-model="item.value"
                    type="textarea"
                    autosize
                    placeholder="请输入内容"
                  />
                  <el-checkbox :label="item.selectNumber">正确</el-checkbox>
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deleteData(index)"
                    style="width: 73px"
                    >删除</el-button
                  >
                </el-form-item>
              </div>
            </el-checkbox-group>
            <el-checkbox-group
              v-model="checkList"
              @change="changeCheckbox"
              :max="max"
              v-if="form.theType == 3"
            >
              <div v-for="(item, index) in options2" :key="index">
                <el-form-item :label="item.selectNumber" class="option">
                  <el-input
                    v-model="item.value"
                    type="textarea"
                    autosize
                    placeholder="请输入内容"
                  />
                  <el-checkbox :label="item.selectNumber">正确</el-checkbox>
                  <el-button
                    type="danger"
                    size="mini"
                    @click="deleteData(index)"
                    style="width: 73px"
                    >删除</el-button
                  >
                </el-form-item>
              </div>
            </el-checkbox-group>
            <el-form-item v-if="form.theType != 3" style="display: flex; justify-content: flex-end">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="add"
                >添加</el-button
              >
            </el-form-item>
            <el-form-item label="解析" prop="analysis">
              <el-input
                type="textarea"
                autosize
                placeholder="请输入内容"
                v-model="form.analysis"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="图片路径" prop="thePic">
              <el-input v-model="form.thePic" placeholder="请输入路径" />
            </el-form-item>
            <el-form-item label="视频路径" prop="theVideo">
              <el-input v-model="form.theVideo" placeholder="请输入路径" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog
          :title="upload.title"
          :visible.sync="upload.open"
          width="400px"
          append-to-body
        >
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <el-button
                type="warning"
                plain
                size="mini"
                @click="importTemplate"
                >下载模板</el-button
              >
            </div>
            <div class="el-upload__tip" style="color: red" slot="tip">
              提示：仅允许导入“xls”或“xlsx”格式文件！
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { getPage, listData, getData, delData, addData, updateData, delMultiData, getSelect, getEnable } from "@/api/check/problemBaseAdmin";
import { getDict, getQuestionType } from "@/api/select";

const TYPE = ["A", "B", "C", "D", "E", "F"];
// const TYPE = ['1', '2', '3', '4', '5', '6'];
export default {
  name: "problemBaseAdmin",
  data() {
    return {
      treeOptions: [],
      currentId: null,
      currentVal: '',
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      theTypeOptions: [], //题型
      quesCateOptions: [], //试题分类
      loading: true,
      tableList: [],
      total: 0,
      ids: [],
      single: true,
      multiple: true,
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        category: undefined,
        theType: undefined,
        keywords: undefined,
      },
      showSearch: true,
      title: "",
      open: false,
      form: {
        deptId1: null,
        deptId2: null,
        userName: null,
        nickName: null,
        roleSort: 0,
      },
      rules: {
        categoryId: [
          { required: true, message: "请选择试题分类", trigger: "change" },
        ],
        subject: [
          { required: true, message: "试题标题不能为空", trigger: "blur" },
        ],
        theType: [{ required: true, message: "请选择题型", trigger: "change" }],
        /* answer: [
          { required: true, message: "请选择答案", trigger: "change" },
        ] */
      },
      options: [],
      options2: [
        { selectNumber: "A", value: "对" },
        { selectNumber: "B", value: "错" },
      ],
      checkList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        // headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        url: "",
      },
    };
  },
  computed: {
    max() {
      console.log('---max-----------------------')
      if (this.form.theType === 1) return 1;
      //单选
      else return this.options.length;
    },
  },
  watch: {
    // 根据名称筛选树
    treeName(val) {
      this.$refs.tree.filter(val);
    },
  },
  components: {
    Treeselect,
  },
  created() {
    this.getPageInfo();
    this.getDialogSelect()
  },
  methods: {
    getPageInfo() {
      getPage(this.queryParams).then((response) => {
        this.treeOptions = response.result.data;
        if (this.currentId === null) {
          //首次进入当前页面
          this.currentId = response.result.data[0].id; //将节点id赋值给上级id
          this.currentVal = response.result.data[0].label; 
        }
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）（第一条）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        this.getList();
      });
    },
    getList() {
      this.loading = true;
      this.queryParams.category = this.currentId;
      listData(this.queryParams).then((response) => {
        this.tableList = response.result.rows;
        this.total = response.result.total;
        this.loading = false;
      });
    },
    getPageSelect() {
      getDict(18, 0).then((response) => { //18-试题分类
        this.quesCateOptions = response.result.data;
      });
    },
    getDialogSelect() {
      if (this.theTypeOptions.length>0) {
        this.form.theType = this.theTypeOptions[0].id
      }else {
        getQuestionType().then(res => {
          this.theTypeOptions = res.result.data
          if (this.theTypeOptions.length>0) {
            this.form.theType = this.theTypeOptions[0].id
          }
        })
      }
    },
    handleNodeClick(data) {
      this.currentId = data.id;
      this.getList();
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.options = [
        { selectNumber: "A", value: "" },
        { selectNumber: "B", value: "" },
      ];
      this.open = true;
      this.title = "添加";
    },
    handleUpdate(row) {
      this.reset();
      this.options = [];
      const theId = row.theid;
      getData(theId).then((response) => {
        console.log("response.result", response.result);
        this.form = response.result;

        // 'theType': 1, //题型 1-单选 2-多选 3-判断 4-填空
        // answer: "1235"
        // response.result.answer = "A.,B."; //先定死，接口改了再改
        this.checkList = response.result.answer.split("|||");
        // this.checkList = response.result.answer.split(",");
        let optionsArr = JSON.parse(response.result.options);
        console.log('optionsArr--修改---',optionsArr)
        optionsArr.forEach((ele) => {
          this.options.push({
            selectNumber: String(ele.val),
            value: ele.title,
          });
        });
        console.log('this.options--修改---',this.options)
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      let optionsArr = [], checkedStr = "";
      if (this.form.theType===3) {//填空题
        this.options = this.options2
      }
      this.options.forEach((ele) => {
        optionsArr.push({ val: ele.selectNumber, title: ele.value });
      });
      if (this.form.theType == 4) {  //填空
        checkedStr = optionsArr.map((item) => item.title).join("|||");
      }else {
        // .sort().join("")  英文正序，转为字符串
        console.log('this.checkList--1---',this.checkList)
        checkedStr = this.checkList.sort().join("|||");
        console.log('this.checkList--2---',this.checkList)
        console.log('checkedStr',checkedStr)
      }

      console.log('this.options--提交---',this.options)

      if (optionsArr.title == "") {
        return this.msgError("请输入选项");
      } else if (this.form.theType != 4 && checkedStr == "") {  //不是填空题，而且没有选择答案
        return this.msgError("请选择答案");
      }

      this.form.options = JSON.stringify(optionsArr);
      this.form.answer = checkedStr;
      
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.theid != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        tid: this.currentId,
        categoryId: this.currentId,
        categoryVal: this.currentVal,
        subject: undefined,
        theType: 1,
        analysis: undefined,
        thePic: undefined,
        theVideo: undefined,
        sort: 0,
        publisherId: this.$store.state.userInfo.theid, //发布人id
        publisher: this.$store.state.userInfo.thename, //发布人
      };
      this.checkList = []
      this.getDialogSelect()
      this.resetForm("form");
    },
    handleDelete(row) {
      const theId = row.theid || this.ids.join(",");
      console.log("--theId", theId);
      if (row.theid) {
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            // 调接口
            return delData(theId);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          });
      } else {
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            // 调接口
            return delMultiData(theId);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          });
      }
    },
    handleStatusChange(row) {
      console.log("row.enable--1--", row.enable);
      let text = row.enable === 1 ? "启用" : "停用";
      this.$confirm('是否确认' + text + '"?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口 改变状态值
          return getEnable(row.theid, row.enable);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.enable = row.enable === 1 ? 0 : 1;
          console.log("row.enable--2--", row.enable);
        });
    },

    // 答案 添加 删除
    // 赋值字母
    onchangeSelect() {
      this.checkList = [];
      this.options = this.options.map((item, index) => {
        item.selectNumber = TYPE[index];
        return item;
      });
    },
    add() {
      if (this.options.length + 1 > 6) {
        this.$alert("最多输入6项");
        return;
      } else {
        this.options.push({
          value: "",
        });
      }
      this.onchangeSelect();
    },
    // 删除
    deleteData(index) {
      if (this.options.length - 1 < 1) {
        this.$alert("至少输入1项");
        return;
      } else {
        this.options.splice(index, 1);
      }
      this.onchangeSelect();
    },
    /** 导出 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm("是否确认导出?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口导出表
          // return exportRole(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 导入 */
    handleImport() {
      this.upload.title = "xx导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      /* importTemplate().then(response => {
        this.download(response.msg);
      }); */
    },
    findTheType(val) {
      if (this.theTypeOptions.length > 0) {
        let value = val
          ? this.theTypeOptions.find((ele) => ele.id === val).label
          : "";
        return value;
      }
    },
    selectTree(val) {
      if (this.treeOptions.length > 0) {
        this.form.categoryVal = val.label;
      }
    },
    changeTheType(val) {
      //切换题型
      this.checkList = [];
    },
    changeCheckbox(val) {
      console.log('val--',val)
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.theid);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>

<style scoped lang="scss">
.option {
  display: flex;

  .el-checkbox {
    margin: 0 20px;
  }
  /deep/ .el-form-item__content {
    display: flex;
    margin-left: 0 !important;
    width: 90%;
  }
}

.warning {
  color: red;
  font-size: 12px;
}


.hide4 {
  /deep/ .el-form-item__label {
    opacity: 0;
  }
  /deep/ .el-checkbox {
    opacity: 0;
  }
}
</style>
